package main

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"time"
)

var (
	dingtalk_URL      = "https://oapi.dingtalk.com/robot/send?access_token="
	dingtalk_Token    = ""
	dingtalk_Timeout  = 5 * time.Second
	dingtalk_BodyType = "application/json;charset=UTF-8"
	dingtalk_MsgType  = "markdown"
)

type dingtalkContext struct {
	MsgType  string `json:"msgtype"`
	Markdown struct {
		Title string `json:"title"`
		Text  string `json:"text"`
	} `json:"markdown"`
}

func Dingtalk(title string, text string) error {
	if dingtalk_Token == "" {
		return errors.New("Missing Dingtalk Token")
	}

	clt := &http.Client{
		Timeout: dingtalk_Timeout,
	}

	data := &dingtalkContext{}
	data.MsgType = dingtalk_MsgType
	data.Markdown.Title = title
	data.Markdown.Text = text

	dataByte, err := json.Marshal(data)
	if err != nil {
		return err
	}

	rsp, err := clt.Post(dingtalk_URL+dingtalk_Token, dingtalk_BodyType, bytes.NewReader(dataByte))
	if err != nil {
		return err
	}
	defer rsp.Body.Close()

	if rsp.StatusCode != http.StatusOK {
		return fmt.Errorf("unexpected response, code %d", rsp.Status)
	}

	return nil
}

func SetDingtalkToken(token string) {
	dingtalk_Token = token
}

func main() {
	SetDingtalkToken("")

	err := Dingtalk("WARNING", "just a joke.")
	if err != nil {
		panic(err)
	}
}
